<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col size="84">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch"
                 label-width="68px">
          <el-form-item style="margin-left: -28px" label="姓名" prop="ckName">
            <el-input v-model="queryParams.ckName" placeholder="请输入姓名" clearable style="width: 140px"
                      @keyup.enter.native="handleQuery"/>
          </el-form-item>
          <el-form-item label="身份证号" prop="ckIdCard">
            <el-select
              v-model="queryParams.ckIdCard"
              filterable
              remote
              :remote-method="handleSearch"
              placeholder="请输入身份证后6位"
            >
              <el-option
                v-for="item in options"
                :key="item.idCard"
                :label="formatIdCard(item.idCard)"
                :value="item.idCard"
              />
            </el-select>
          </el-form-item>
          <el-form-item style="margin-left: -15px" label="手机号" prop="ckPhoneNumber">
            <el-input v-model="queryParams.ckPhoneNumber" placeholder="请输入手机号" clearable style="width: 160px"
                      @keyup.enter.native="handleQuery"/>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
                       v-hasPermi="['system:student:add']">新增
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple"
                       @click="handleDelete" v-hasPermi="['system:student:remove']">删除
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="info" plain icon="el-icon-upload2" size="mini" @click="handleImport"
                       v-hasPermi="['system:student:import']">导入
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
                       v-hasPermi="['system:student:export']">导出
            </el-button>
          </el-col>
        </el-row>

        <!-- 列表 -->
        <el-table v-loading="loading" :data="userList" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="50" align="center"/>
          <el-table-column label="姓名" align="center" key="ckName" prop="ckName"
                           :show-overflow-tooltip="true" fixed="left"/>
          <el-table-column label="身份证号" align="center" key="ckIdCard" prop="ckIdCard"
                           width="180"/>
          <el-table-column label="手机号码" align="center" key="ckPhoneNumber" prop="ckPhoneNumber"
                           width="120"/>
          <el-table-column label="邮箱" align="center" key="ckEmail" prop="ckEmail"
                           width="160">
          </el-table-column>

          <el-table-column label="乘客编号" align="center" key="specialNumber" prop="specialNumber"
                           width="120">
          </el-table-column>

          <el-table-column label="创建者" align="center" key="createBy" prop="createBy"
                           width="120">
          </el-table-column>
          <el-table-column label="创建时间" align="center" prop="createTime" width="160">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.createTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="更新者" align="center" key="updateBy" prop="updateBy"
                           width="120">
          </el-table-column>
          <el-table-column label="更新时间" align="center" prop="updateTime" width="160">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.updateTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="备注" align="center" key="remark" prop="remark"
                           width="120">
          </el-table-column>
          <el-table-column fixed="right" label="操作" align="center" width="160"
                           class-name="small-padding fixed-width">
            <template slot-scope="scope" v-if="scope.row.id !== 0">
              <el-button  size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
                         v-hasPermi="['system:student:edit']">修改
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"
                    :limit.sync="queryParams.pageSize" @pagination="getList"/>
      </el-col>
    </el-row>

    <!-- 添加或修改用户配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="姓名" prop="ckName">
              <el-input v-model="form.ckName" placeholder="请输入姓名" maxlength="5"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="身份证号" prop="ckIdCard">
              <el-input v-model="form.ckIdCard" placeholder="请输入身份证号" maxlength="18"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="手机号" prop="ckPhoneNumber">
              <el-input v-model="form.ckPhoneNumber" placeholder="请输入手机号" maxlength="11"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="邮箱" prop="ckEmail">
              <el-input v-model="form.ckEmail" placeholder="请输入邮箱" maxlength="50"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
<!--          <el-col :span="12" v-show="false">-->
<!--            <el-form-item label="乘客编号" prop="specialNumber">-->
<!--              <el-input v-model="form.specialNumber" placeholder="请输入乘客编号" maxlength="2"/>-->
<!--            </el-form-item>-->
<!--          </el-col>-->
          <el-col :span="24">
            <el-form-item label="备注">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 用户导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload ref="upload" :limit="1" accept=".xlsx, .xls" :headers="upload.headers"
                 :action="upload.url + '?updateSupport=' + upload.updateSupport" :disabled="upload.isUploading"
                 :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :auto-upload="false" drag>
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <div class="el-upload__tip" slot="tip">
            <el-checkbox v-model="upload.updateSupport"/>
            是否更新已经存在的用户数据
          </div>
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size: 12px; vertical-align: baseline"
                   @click="importTemplate">下载模板
          </el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listStudent,
  getStudent,
  addStudent,
  delStudent,
  updateStudent
} from "@/api/ground/student";
import { getCkBaseIdCardInfo } from '@/api/ckxl/ck'
import { debounce } from 'lodash';
import {getToken} from "@/utils/auth";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import "splitpanes/dist/splitpanes.css";

export default {
  name: "Student",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 用户表格数据
      userList: null,
      // 弹出层标题
      title: "",
      // 部门树选项
      deptOptions: undefined,
      // 是否显示弹出层
      open: false,
      // 日期范围
      dateRange: [],
      // 表单参数
      form: {},
      defaultProps: {
        children: "children",
        label: "label"
      },
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: {Authorization: "Bearer " + getToken()},
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/student/people/importData"
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        ckName: undefined,
        ckIdCard: undefined,
        ckPhoneNumber: undefined,
      },
      // 表单校验
      rules: {
        ckName: [
          {required: true, message: "姓名不能为空", trigger: "blur"}
        ],
        ckIdCard: [
          {required: true, message: '请输入身份证号码', trigger: 'blur'},
          {
            pattern: /^[1-9]\d{5}(18|19|20)?\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}(\d|[Xx])$/,
            message: '身份证号码格式不正确', trigger: 'blur'
          }
        ],
        ckEmail: [
          {
            required: true,
            type: "email",
            message: "请输入正确的邮箱地址",
            trigger: ["blur", "change"]
          }
        ],
        ckPhoneNumber: [
          {
            required: true,
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: "请输入正确的手机号",
            trigger: "blur"
          }
        ],
        // specialNumber: [
        //   {required: true, message: "乘客编号不能为空", trigger: "blur"}
        // ]
      },
      // 选中数组
      ckNames: [],
      //默认新增
      addFlag: true,
      isShow: false,
      options: [{
        label:"",
        value:""
      }],
    };
  },
  watch: {},
  created() {
    this.getList();
  },
  methods: {
    /** 查询学生信息列表 */
    getList() {
      this.loading = true;
      listStudent(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
          this.userList = response.rows;
          this.total = response.total;
          this.loading = false;
        }
      );
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        ckName: undefined,
        ckIdCard: undefined,
        specialNumber: undefined,
        ckPhoneNumber: undefined,
        ckEmail: undefined,
        remark: undefined,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.queryParams.deptId = undefined;
      this.$refs.tree.setCurrentKey(null);
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.ckNames = selection.map(item => item.ckName);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.addFlag = true;
      this.reset();
      this.open = true;
      this.title = "添加学生";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.addFlag = false;
      this.reset();
      const id = row.id || this.ids;
      getStudent(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改乘客";
      });
    },

    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != undefined) {
            updateStudent(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addStudent(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const idBases = row.id || this.ids;
      this.$modal.confirm('是否确认删除乘客姓名为"' + this.ckNames + '"的数据项？').then(function () {
        return delStudent(idBases);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },



    /** 导出按钮操作 */
    handleExport() {
      this.download('student/people/export', {
        ...this.queryParams
      }, `user_${new Date().getTime()}.xlsx`)
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "用户导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download('student/people/importTemplate', {}, `student_template_${new Date().getTime()}.xlsx`)
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", {dangerouslyUseHTMLString: true});
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },

    // 防抖处理（500ms内仅触发一次）
    handleSearch: debounce(function(query) {
      if(query.trim().length >6){
        const keyword = query.trim().slice(0, 6).toUpperCase();
        this.$modal.msgError("最多只能输入6个字符");
        this.queryParams.ckIdCard = keyword;
        return;
      }
      // 校验格式：6位数字或X
      if (!/^[0-9X]{6}$/.test(query.trim())) {
        this.options = [];
        return;
      }
      const lastSixIdNum = query.trim();
      getCkBaseIdCardInfo(lastSixIdNum).then(response => {
        if (response.data != null) {
          this.options = response.data
        }
      }).catch(() => {
        this.options = [];
      });
    }, 500),

    // 格式化显示身份证号（如：410*****123456）
    formatIdCard(idCard) {
      if(idCard != null){
        return idCard.replace(/(\d{4})\d+(\d{6})/, '$1*****$2');
      }
    },

  }
};
</script>
